const jwt = require("jsonwebtoken");
const auth = require("basic-auth");
const result = require("../config/handle");
const { security } = require("./tokentime");

class Auth {
  constructor() {}
  get m() {
    return async (ctx, next) => {
      const token = auth(ctx.req);
      if (!token || !token.name) {
        throw new result({ errorcode: "401", msg: "没有权限" }, 401);
      }
      try {
        var authCode = jwt.verify(token.name, security.secretkey);
      } catch (error) {
        if (error.name == "TokenExpiredError") {
          throw new result({ errorcode: "401", msg: "请重新登陆" }, 401);
        }
        throw new result({ errorcode: "401", msg: "没有权限" }, 401);
      }
      ctx.auth = {
        uid : authCode.uid
      }
      await next()
    };
  }
}
module.exports = { Auth };
